# encoding=utf-8
import argparse
import datetime
import json
import logging
import os
import time
import traceback
import requests

parser = argparse.ArgumentParser()
parser.add_argument("--remote", type=str, default="http://127.0.0.1:30012/run/dense121/five")
parser.add_argument("--workdir", type=str, default="workdir")
args = parser.parse_args()
if args.workdir == "" or args.workdir is None:
    print("work dir is empty")
    exit(-1)

remote_api = args.remote
work_dir = args.workdir

from_path = os.path.join(work_dir, "user_input")
csv_name = "{}.csv".format(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
csv_path = os.path.join(work_dir, csv_name)


def run_remote(abs_file_path: str):
    t1 = time.perf_counter()
    f = {"file": open(abs_file_path, 'rb')}
    try:
        res = requests.post(remote_api, files=f)
        t2 = time.perf_counter()
        print("{} cost time, {}s".format(os.path.basename(abs_file_path), t2 - t1))

        code = res.status_code
        if code != 200:
            logging.error(res.content)
            return {
                'index': 0,
                'pie': [-1]
            }
        else:
            return json.loads(res.content.decode("utf-8"))
    except Exception as e:
        logging.error(traceback.format_exc())
        return None


def main():
    file_names = os.listdir(from_path)
    with open(csv_path, "w") as csv_file:
        csv_file.write("name,index,possible\n")

        for each_name in file_names:
            abs_path = os.path.join(from_path, each_name)
            out = run_remote(abs_path)
            if out is not None:
                index = out["index"]
                possible = out["pie"][index]

                csv_file.write("{},{},{}\n".format(each_name, index, possible))


if __name__ == '__main__':
    main()
